package com.mdd.admin.service.course.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.course.ICourseCommentService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.course.CourseCommentParam;
import com.mdd.admin.vo.course.CourseCommentListVo;
import com.mdd.admin.vo.course.CourseCommentDetailVo;
import com.mdd.admin.vo.course.CourseListVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.course.Course;
import com.mdd.common.entity.course.CourseComment;
import com.mdd.common.entity.course.CourseCommentImage;
import com.mdd.common.mapper.course.CourseCommentImageMapper;
import com.mdd.common.mapper.course.CourseCommentMapper;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.StringUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.common.config.GlobalConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 评论实现类
 * @author panweiliang
 */
@Service
public class CourseCommentServiceImpl implements ICourseCommentService {
        
    @Resource
    CourseCommentMapper courseCommentMapper;

    @Resource
    CourseCommentImageMapper courseCommentImageMapper;

    /**
     * 评论列表
     *
     * @author panweiliang
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<CourseCommentListVo>
     */
    @Override
    public PageResult<CourseCommentListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        MPJQueryWrapper<CourseComment> mpjQueryWrapper = new MPJQueryWrapper<CourseComment>()
                .selectAll(CourseComment.class)
                .select("user.sn as userSn, user.nickname as userNickname, user.real_name as userRealName, user.avatar as userAvatarUrl, course.name as courseName, course.cover as courseCoverPath")
                .innerJoin("?_user user ON user.id=t.user_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .innerJoin("?_course course ON course.id=t.course_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .orderByDesc(Arrays.asList("t.id"));

        courseCommentMapper.setSearch(mpjQueryWrapper, params, new String[]{
                "like:courseName@course.name:str",
                "=:courseScore@t.course_score:int",
                "datetime:startTime-endTime@t.create_time:str"
        });

        if (StringUtil.isNotEmpty(params.get("keyword"))) {
            String keyword = params.get("keyword");
            mpjQueryWrapper.nested(wq->wq
                    .like("user.nickname", keyword).or()
                    .like("user.mobile", keyword));
        }

        if (StringUtil.isNotEmpty(params.get("replyStatus"))) {
            String replyStatus = params.get("replyStatus");
            if ("1".equals(replyStatus)) {
                //待回复
                mpjQueryWrapper.nested(wq->wq
                        .isNull("reply").or()
                        .eq("reply", ""));
            } else {
                //已回复
                mpjQueryWrapper.nested(wq->wq
                        .isNotNull("reply").ne("reply", ""));
            }
        }

        IPage<CourseCommentListVo> iPage = courseCommentMapper.selectJoinPage(new Page<>(page, limit), CourseCommentListVo.class, mpjQueryWrapper);

        for(CourseCommentListVo item : iPage.getRecords()) {

            QueryWrapper<CourseCommentImage> commentImgQueryWrapper = new QueryWrapper<>();
            commentImgQueryWrapper.eq("comment_id", item.getId());

            List<CourseCommentImage> commentImageList = courseCommentImageMapper.selectList(commentImgQueryWrapper);

            List<String> commentImages = new LinkedList<>();

            commentImageList.forEach(imageItem -> {
                commentImages.add(UrlUtil.toAbsoluteUrl(imageItem.getUri()));
            });

            item.setCommentImgs(commentImages);
            item.setCourseCoverPath(UrlUtil.toAbsoluteUrl(item.getCourseCoverPath()));
            item.setUserAvatarUrl(UrlUtil.toAbsoluteUrl(item.getUserAvatarUrl()));
            item.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            item.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    /**
     * 评论详情
     *
     * @author panweiliang
     * @param id 主键参数
     * @return CourseComment
     */
    @Override
    public CourseCommentDetailVo detail(Integer id) {
        CourseComment model = courseCommentMapper.selectOne(
                new QueryWrapper<CourseComment>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        CourseCommentDetailVo vo = new CourseCommentDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 评论编辑
     *
     * @author panweiliang
     * @param courseCommentParam 参数
     */
    @Override
    public void edit(CourseCommentParam courseCommentParam) {
        CourseComment model = courseCommentMapper.selectOne(
                new QueryWrapper<CourseComment>()
                    .eq("id",  courseCommentParam.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(courseCommentParam.getId());
        model.setOrderId(courseCommentParam.getOrderId());
        model.setCourseId(courseCommentParam.getCourseId());
        model.setUserId(courseCommentParam.getUserId());
        model.setCourseScore(courseCommentParam.getCourseScore());
        model.setComment(courseCommentParam.getComment());
        model.setReply(courseCommentParam.getReply());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        courseCommentMapper.updateById(model);
    }

    @Override
    public void reply(CourseCommentParam courseCommentParam) {
        CourseComment model = courseCommentMapper.selectOne(
                new QueryWrapper<CourseComment>()
                        .eq("id",  courseCommentParam.getId())
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在!");

        String replyContent = courseCommentParam.getReply();

        Assert.isTrue(StringUtil.isNotEmpty(replyContent), "请填写回复内容，回复内容不能为空");

        model.setReply(replyContent);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        courseCommentMapper.updateById(model);
    }

    /**
     * 评论删除
     *
     * @author panweiliang
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        CourseComment model = courseCommentMapper.selectOne(
                new QueryWrapper<CourseComment>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        courseCommentMapper.delete(new QueryWrapper<CourseComment>().eq("id", id));

        courseCommentImageMapper.delete(new QueryWrapper<CourseCommentImage>().eq("comment_id", id));
    }

}
